package com.panda.controller.captcha;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.panda.utils.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "获取验证码控制器")
@Validated
public class CaptchaController {

    @Autowired
    private RedisCache redisCache;

    //用来生成验证码的接口，HttpServletResponse 用于将生成的验证码响应到页面展示
    @GetMapping("/captcha")
    @ApiOperation(value = "获取验证码")
    public void getCode(HttpServletResponse response, @NotBlank(message = "验证码id不能为空") String captchaId) {
        //验证码工具类
        //HuTool定义图形验证码的长和宽,验证码的位数，干扰线的条数
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 30, 6, 10);
        System.out.println(lineCaptcha.getCode() + "验证码的值");
        //把验证码存入redis, 一分钟过期
        redisCache.setCacheObject("captcha:" + captchaId, lineCaptcha.getCode(), 60, TimeUnit.SECONDS);
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            lineCaptcha.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
